package com.config;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.HttpMethod;
import com.bean.ResponseBean;
import com.pojo.Admin;
import com.service.AdminService;
import com.util.JwtUtil;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${management.server.port}")
    private int shutdownPort;

    @Autowired
    private AdminService adminService;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
//            String path = request.getServletPath();
//            System.out.println("接口："+path);

            if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
                return true;
            }
            if (!(handler instanceof HandlerMethod)) {
                return true;
            }

            response.setContentType("text/html;charset=utf-8");
            ResponseBean responseBean = new ResponseBean(403, "登陆失效", null);
            String str = JSONObject.toJSONString(responseBean);

            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
//            String url = ((HandlerMethod) handler).getMethod().getName();
//            System.out.println("接口名称："+url);

            //优雅关机接口
            if (request.getServerPort()==shutdownPort){
                return true;
            }
            // 判断接口是否需要登录
            NoLogin methodAnnotation = method.getAnnotation(NoLogin.class);
            if (methodAnnotation != null) {
                return true;
            }

            String token;
            try {
                token = request.getHeader("token");
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            if (StringUtil.isNull(token)){
                try {
                    response.getWriter().println(str);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                return false;
            }
            String uid = JwtUtil.getUsername(token);
            Admin admin = adminService.getById(uid);
            if (admin == null){
                try {
                    response.getWriter().println(str);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("text/html;charset=utf-8");
            ResponseBean responseBean = new ResponseBean(403, "登陆失效", null);
            String str = JSONObject.toJSONString(responseBean);
            try {
                response.getWriter().println(str);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } finally {

        }
        return false;//如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }
}